// NetClientDlg.cpp : implementation file
//

#include "stdafx.h"
#include "NetClient.h"
#include "NetClientDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CNetClientDlg dialog
#include "TG_PlaySDK.h"
#include "TG_NetSDK.h"


#ifdef _DEBUG
#pragma comment(lib, "TGPlaySDKd.lib")
#pragma comment(lib, "TGNetClientSDKd.lib")
#else
#pragma comment(lib, "TGPlaySDK.lib")
#pragma comment(lib, "TGNetClientSDK.lib")
#endif


#define WM_USER_MSG	WM_USER + 0x100
#define WM_ANCHOR	WM_USER + 0x101

#define MSG_STREAM_DISCONNECT 1


CNetClientDlg::CNetClientDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CNetClientDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_PlayWnd = NULL;


	m_hPlayer     = NULL;
	m_hLogin      = NULL;
	m_hRealStream = NULL;
	m_hAnchor = NULL;
#ifdef dkq_write_264
	m_h264 = NULL;
#endif
}

BOOL CNetClientDlg::DestroyWindow()
{
	// TODO: Add your specialized code here and/or call the base class

	UnInitialize();

	if( NULL != m_PlayWnd )
	{
		delete m_PlayWnd;
		m_PlayWnd = NULL;
	}

#ifdef dkq_write_264
	if( NULL != m_h264 )
	{
		fclose(m_h264);
		m_h264 = NULL;
	}
#endif

	return CDialog::DestroyWindow();
}


void CNetClientDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CNetClientDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BTN_StartPlayStram, &CNetClientDlg::OnBnClickedBtnStartplaystram)
	ON_BN_CLICKED(IDC_BTN_StopPlayStream, &CNetClientDlg::OnBnClickedBtnStopplaystream)

	ON_MESSAGE(WM_USER_MSG , OnUserMsg)

	ON_BN_CLICKED(IDC_BTN_GET_ANCHOR, &CNetClientDlg::OnBnClickedBtnGetAnchor)
END_MESSAGE_MAP()


// CNetClientDlg message handlers

BOOL CNetClientDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	SetDlgItemText(IDC_EDIT_IP,"192.168.1.105");
	SetDlgItemInt(IDC_EDIT_DataPort,9001);
	SetDlgItemInt(IDC_EDIT_InfoPort,9002);
	
	( (CButton*)GetDlgItem(IDC_RADIO_TCP) )->SetCheck( 1 );


	GetDlgItem(IDC_BTN_StopPlayStream)->EnableWindow(FALSE);


	CRect rt;
	GetDlgItem(IDC_STATIC_IMAGE)->GetWindowRect(&rt);
	ScreenToClient(&rt);

	m_PlayWnd = new CWnd();
	m_PlayWnd->Create(NULL, NULL, WS_CHILD | WS_VISIBLE , rt, this, 0);
	
	Initialize();


	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CNetClientDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CNetClientDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CNetClientDlg::UnInitialize()
{
	if( NULL != m_hRealStream )
	{
		TG_Net_StopRealStream(m_hRealStream);
		m_hRealStream = NULL;
	}
	TG_Net_Cleanup();

	if( NULL != m_hPlayer )
	{
		TG_Play_ReleasePlayer( m_hPlayer);
		m_hPlayer = NULL;
	}
	TG_Play_Cleanup();
}

void CNetClientDlg::Initialize()
{
	TG_Net_Init();
	TG_Net_SetConnectTime(5000, 5);

	TG_Play_Init();

	TG_Play_InitPlayer(m_PlayWnd->m_hWnd, m_hPlayer);
}


void CNetClientDlg::OnBnClickedBtnStartplaystram()
{
	int nSelectAnchor = ((CListBox*)GetDlgItem(IDC_LIST_ANCHOR))->GetCurSel();
	if(nSelectAnchor < 0)
	{
		MessageBox(_T("Please select an anchor first!"), _T("Tip"), MB_ICONEXCLAMATION);
		return;
	}
	TG_REALSTREAM_INFO xInfo;
	sprintf(xInfo.xConnectInfo.xUserInfo.szUserName,"admin");
	sprintf(xInfo.xConnectInfo.xUserInfo.szPassword,"admin");

	GetDlgItemText( IDC_EDIT_IP,xInfo.xConnectInfo.szServerIP,TG_IPADDR_MAX );
	xInfo.xConnectInfo.nServerPort = (UINT16)GetDlgItemInt(IDC_EDIT_DataPort);

	xInfo.xConnectInfo.xAnchorInfo.dwUserID = (DWORD)((CListBox*)GetDlgItem(IDC_LIST_ANCHOR))->GetItemData(nSelectAnchor);

	xInfo.xConnectInfo.nLinkProtocol       = ( (CButton*)GetDlgItem(IDC_RADIO_TCP) )->GetCheck()? TG_NET_PROTOCOL_TCP:TG_NET_PROTOCOL_UDP;

	xInfo.xConnectInfo.nTimeOut = 5000;

	xInfo.funCallBack   = RealDataCallBack;
	xInfo.nContext      = 456;
	xInfo.pContext      = this;

	TGERR_CODE errCode = TG_Net_StartRealStream(&xInfo, m_hRealStream);
	if(TG_ERR_SUCCESS == errCode) 
	{
		char sText[100]={0};
		sprintf(sText,"connect success!");
		((CListBox*)GetDlgItem(IDC_LIST_INFO))->AddString(sText);

		GetDlgItem(IDC_BTN_StartPlayStram)->EnableWindow(FALSE);
		GetDlgItem(IDC_BTN_StopPlayStream)->EnableWindow(TRUE);
	} 
	else 
	{
		char sText[100]={0};
		sprintf(sText,"connect failure!");
		((CListBox*)GetDlgItem(IDC_LIST_INFO))->AddString(sText);
		
		GetDlgItem(IDC_BTN_StartPlayStram)->EnableWindow(TRUE);
		GetDlgItem(IDC_BTN_StopPlayStream)->EnableWindow(FALSE);
	}

}

void CNetClientDlg::OnBnClickedBtnStopplaystream()
{
	if( NULL != m_hRealStream )
	{
		TG_Net_StopRealStream(m_hRealStream);
		m_hRealStream = NULL;
	}

	GetDlgItem(IDC_BTN_StartPlayStram)->EnableWindow(TRUE);
	GetDlgItem(IDC_BTN_StopPlayStream)->EnableWindow(FALSE);
}


BOOL CNetClientDlg::RealDataCallBack(void *pBufferData, UINT32 nBufSize, UINT32 nContext, void *pContext)
{
	if( NULL != pContext )
	{
        return ( (CNetClientDlg*)pContext )->RealData( pBufferData,nBufSize,nContext);
	}
	

	return FALSE;
}

BOOL CNetClientDlg::RealData(void *pBufferData, UINT32 nBufSize, UINT32 nContext)
{
	if( NULL != pBufferData  && nBufSize > 0 && NULL != m_hPlayer )
	{
#ifdef dkq_write_264
		if( NULL == m_h264 )
		{
			m_h264 = fopen("test_client.264","wb");
		}
#endif

#ifdef dkq_write_264
		if( NULL != m_h264 )
		{
			fwrite(pBufferData,1,nBufSize,m_h264);
		}
#endif

		TG_Play_InputStream(m_hPlayer, pBufferData, nBufSize, true);
	}
	else
	{
		::PostMessage(m_hWnd,WM_USER_MSG,MSG_STREAM_DISCONNECT,NULL);
	}

	return TRUE;
}

BOOL CALLBACK CNetClientDlg::AnchorDataCallBack(void *pBufferData, UINT32 nBufSize, UINT32 nContext, void *pContext)
{
	if( NULL != pContext )
	{
		return ( (CNetClientDlg*)pContext )->AnchorData( pBufferData,nBufSize,nContext);
	}


	return FALSE;
}

BOOL CNetClientDlg::AnchorData(void *pBufferData, UINT32 nBufSize, UINT32 nContext)
{
	PostMessage(WM_ANCHOR, (WPARAM)nBufSize, (LPARAM)pBufferData);
	return TRUE;
}

LRESULT CNetClientDlg::OnUserMsg(WPARAM wParam, LPARAM lParam)
{
	switch( wParam )
	{
	case MSG_STREAM_DISCONNECT:
		{
			char sText[100]={0};
			sprintf(sText,"disconnect!");
			((CListBox*)GetDlgItem(IDC_LIST_INFO))->AddString(sText);

			OnBnClickedBtnStopplaystream();
		}
		break;
	default:
		break;
	}

	return 0;
}
void CNetClientDlg::OnBnClickedBtnGetAnchor()
{
	// TODO: Add your control notification handler code here
	TG_GETANCHOR_LOGIN_INFO xInfo;
	sprintf(xInfo.xConnectInfo.xUserInfo.szUserName,"admin");
	sprintf(xInfo.xConnectInfo.xUserInfo.szPassword,"admin");

	GetDlgItemText( IDC_EDIT_IP,xInfo.xConnectInfo.szServerIP,TG_IPADDR_MAX );
	xInfo.xConnectInfo.nServerPort = (UINT16)GetDlgItemInt(IDC_EDIT_InfoPort);

	xInfo.xConnectInfo.xAnchorInfo.dwUserID  = 1;

	xInfo.xConnectInfo.nLinkProtocol       = ( (CButton*)GetDlgItem(IDC_RADIO_TCP) )->GetCheck()? TG_NET_PROTOCOL_TCP:TG_NET_PROTOCOL_UDP;

	xInfo.xConnectInfo.nTimeOut = 5000;

	xInfo.funCallBack   = AnchorDataCallBack;
	xInfo.nContext      = 789;
	xInfo.pContext      = this;

	((CListBox*)GetDlgItem(IDC_LIST_ANCHOR))->ResetContent();

	if(m_hAnchor != NULL)
	{
		TG_GetAnchor_Logout(m_hAnchor);
		m_hAnchor = NULL;
	}
	TGERR_CODE errCode = TG_GetAnchor_Login(&xInfo, m_hAnchor);
	if(TG_ERR_SUCCESS == errCode) 
	{
		char sText[100]={0};
		sprintf(sText,"Get anchor success!");
		((CListBox*)GetDlgItem(IDC_LIST_INFO))->AddString(sText);
		TG_GetAnchor_Refresh(m_hAnchor);
	} 
	else 
	{
		char sText[100]={0};
		sprintf(sText,"Get anchor failure!");
		((CListBox*)GetDlgItem(IDC_LIST_INFO))->AddString(sText);
	}
}

LRESULT CNetClientDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	// TODO: Add your specialized code here and/or call the base class
	if(WM_ANCHOR == message)
	{
		int nBufSize = wParam;
		char* pAnchorList = (char *)lParam;
		if(pAnchorList != NULL)
		{
			int nCount = nBufSize / (TG_USERNAME_LEN + sizeof(DWORD));
			char szAnchor[TG_USERNAME_LEN];
			DWORD dwID = 0;
			int nPos = 0;
			for(int i=0;i<nCount;i++)
			{
				nPos = i *(TG_USERNAME_LEN + sizeof(DWORD));
				strncpy(szAnchor, pAnchorList + nPos, TG_USERNAME_LEN);
				nPos += TG_USERNAME_LEN;
				memcpy(&dwID, pAnchorList + nPos, sizeof(DWORD));
				((CListBox*)GetDlgItem(IDC_LIST_ANCHOR))->AddString(szAnchor);
				((CListBox*)GetDlgItem(IDC_LIST_ANCHOR))->SetItemData(i, dwID);
			}
		}
		TG_GetAnchor_Logout(m_hAnchor);
		m_hAnchor = NULL;
	}
	return CDialog::WindowProc(message, wParam, lParam);
}
